package net.kleinhenz.norabase.client;

import net.kleinhenz.norabase.client.datasource.ChampionsDS;
import net.kleinhenz.norabase.client.datasource.EquipmentDS;
import net.kleinhenz.norabase.client.datasource.RelicDS;
import net.kleinhenz.norabase.client.datasource.SpellDS;
import net.kleinhenz.norabase.shared.model.Rune;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.RootPanel;
import com.smartgwt.client.data.Record;
import com.smartgwt.client.types.SelectionStyle;
import com.smartgwt.client.types.Side;
import com.smartgwt.client.util.BooleanCallback;
import com.smartgwt.client.util.SC;
import com.smartgwt.client.widgets.layout.HLayout;
import com.smartgwt.client.widgets.layout.VLayout;
import com.smartgwt.client.widgets.menu.Menu;
import com.smartgwt.client.widgets.menu.MenuItem;
import com.smartgwt.client.widgets.menu.MenuItemSeparator;
import com.smartgwt.client.widgets.menu.events.MenuItemClickEvent;
import com.smartgwt.client.widgets.tab.TabSet;
import com.smartgwt.client.widgets.tab.Tab;
import com.smartgwt.client.widgets.Canvas;
import com.smartgwt.client.widgets.HTMLFlow;
import com.smartgwt.client.widgets.Label;
import com.smartgwt.client.widgets.events.ClickEvent;
import com.smartgwt.client.widgets.events.ClickHandler;
import com.smartgwt.client.widgets.grid.ListGrid;
import com.smartgwt.client.widgets.grid.ListGridField;
import com.smartgwt.client.widgets.grid.ListGridRecord;
import com.smartgwt.client.widgets.grid.SummaryFunction;
import com.smartgwt.client.widgets.toolbar.ToolStrip;
import com.smartgwt.client.widgets.toolbar.ToolStripButton;
import com.smartgwt.client.widgets.toolbar.ToolStripMenuButton;

public class NoraBaseEditor implements EntryPoint {

	private static final String VERSION = "0.0.1 &alpha;";
	
	private static LoginInfo loginInfo = null;

	private final TabSet databaseSet = new TabSet();
	private VLayout body = null;
	
	public void onModuleLoad() {

		if (RootPanel.get("battlegroupEditor")!=null)
			loadEditor();
		else if (RootPanel.get("runeViewer")!=null)
			loadRuneViewer();
		else if (RootPanel.get("battlegroupViewer")!=null)
			loadBattlegroupViewer();
	}

	private void loadBattlegroupViewer() {

		String id = com.google.gwt.user.client.Window.Location.getParameter("id");
		
		final VLayout body = new VLayout(10);
		body.setWidth("1020px");
		body.setHeight("800px");

		final HTMLFlow name = new HTMLFlow(); 
		body.addMember(name);
		final HTMLFlow desc = new HTMLFlow(); 
		body.addMember(desc);
		final HTMLFlow strat = new HTMLFlow(); 
		body.addMember(strat);

		HLayout runeLayout = new HLayout();
		body.addMember(runeLayout);

		final FrontCard frontCard = new FrontCard();
		final BackCard backCard = new BackCard();
		runeLayout.addMember(frontCard);
		runeLayout.addMember(backCard);		
		final RatingCanvas ratingCanvas = new RatingCanvas(true);
		ratingCanvas.setSize("400px", "100%");
		runeLayout.addMember(ratingCanvas);

		TabSet tabs = new TabSet();
		final BattlegroupTab tab = new BattlegroupTab(id, "Rune List", null);
		tab.addGridClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				ListGridRecord r = ((ListGrid)tab.getPane()).getSelectedRecord();
				if (Rune.CHAMPION.equals(r.getAttributeAsString("type")))
					RuneLoader.loadChampion(r.getAttributeAsInt("id"), frontCard, backCard, null);
				else if (Rune.SPELL.equals(r.getAttributeAsString("type")))
					RuneLoader.loadSpell(r.getAttributeAsInt("id"), frontCard, backCard, null);
				else if (Rune.EQUIPMENT.equals(r.getAttributeAsString("type")))
					RuneLoader.loadSpell(r.getAttributeAsInt("id"), frontCard, backCard, null);
				else if (Rune.RELIC.equals(r.getAttributeAsString("type")))
					RuneLoader.loadSpell(r.getAttributeAsInt("id"), frontCard, backCard, null);
			}
		});
		tabs.addTab(tab);
		body.addMember(tabs);

        BattlegroupServiceAsync service = GWT.create(BattlegroupService.class);
        service.retrieveBattlegroup(id, new AsyncCallback<net.kleinhenz.norabase.shared.model.Battlegroup<Rune>>() {
            public void onFailure(Throwable caught) {
            	SC.say("An error occured while retrieving battlegroup info from the server. Please try again.");
            	return;
            }
            public void onSuccess(net.kleinhenz.norabase.shared.model.Battlegroup<Rune> result) {
            	tab.loadBattlegroup(result);
            	ratingCanvas.loadBattlegroup(result);
            	name.setContents("<div style='font-size:2em;color:#ffffff;text-align:center;'>" + result.getName() + "</div>");
            	if (result.getDesc()!=null)
            		desc.setContents("<div style='font-size:1em;color:#ffffff;text-align:left;'><b>Description</b>: " + result.getDesc() + "</div>");
            	if (result.getStrat()!=null)
            		strat.setContents("<div style='font-size:1em;color:#ffffff;text-align:left;'><b>Strategy</b>: " + result.getStrat() + "</div>");
            }
        });
		
        RootPanel root = RootPanel.get("battlegroupViewer");
        if (root!=null)
        	root.add(body);
	}

	private void loadRuneViewer() {

		String id = com.google.gwt.user.client.Window.Location.getParameter("id");
		String type = null;
		
		final VLayout body = new VLayout(10);
		body.setHeight("800px");
		HLayout runeLayout = new HLayout();
		body.addMember(runeLayout);
		
		final FrontCard frontCard = new FrontCard();
		final BackCard backCard = new BackCard();
		runeLayout.addMember(frontCard);
		runeLayout.addMember(backCard);
		
		final RatingCanvas ratingCanvas = new RatingCanvas(false);
		ratingCanvas.setSize("620px", "100%");
		body.addMember(ratingCanvas);

		if (id!=null && id.length()>1) {
			if (id.startsWith("C") || id.startsWith("c"))
				type = Rune.CHAMPION;
			else if (id.startsWith("E") || id.startsWith("e"))
				type = Rune.EQUIPMENT;
			else if (id.startsWith("S") || id.startsWith("s"))
				type = Rune.SPELL;
			else if (id.startsWith("R") || id.startsWith("r"))
				type = Rune.RELIC;

			id = id.substring(1);
		}
		
		if (Rune.CHAMPION.equals(type))
			RuneLoader.loadChampion(new Integer(id), frontCard, backCard, ratingCanvas);
		else if (Rune.EQUIPMENT.equals(type))
			RuneLoader.loadEquipment(new Integer(id), frontCard, backCard, ratingCanvas);
		else if (Rune.SPELL.equals(type))
			RuneLoader.loadSpell(new Integer(id), frontCard, backCard, ratingCanvas);
		else if (Rune.RELIC.equals(type))
			RuneLoader.loadRelic(new Integer(id), frontCard, backCard, ratingCanvas);

        RootPanel root = RootPanel.get("runeViewer");
        if (root!=null)
        	root.add(body);
	}
	
	private void loadEditor() {
		// Check login status using login service.
		LoginServiceAsync loginService = GWT.create(LoginService.class);
		loginService.login(GWT.getHostPageBaseURL(),
				new AsyncCallback<LoginInfo>() {
					public void onFailure(Throwable error) {
						throw new RuntimeException(error);
					}

					public void onSuccess(LoginInfo result) {
						loginInfo = result;
						if (loginInfo.isLoggedIn()) {
							loadNoraBase();
						} else {
							loadLogin();
						}
					}
				});
	}
	
	private void loadLogin() {

		SC.say("Please <a href=\"" + loginInfo.getLoginUrl() + "\">Login</a> using your Google Account. If you do not have a Google Account, you can create one <a href='https://www.google.com/accounts/NewAccount'>here</a>. This application does not receive or has access to your Google password. It also does not store any information besides your e-mail address registered with your Google Account.");
	}

	private ToolStripMenuButton createMenu(final BattlegroupTabSet bgts) {

		Menu menu = new Menu();
		menu.setShowShadow(true);
		menu.setShadowDepth(10);

		MenuItem exportBGItem = new MenuItem("Export Battlegroup as...");
		Menu exportBGSM = new Menu();
		MenuItem exportBGCSV = new MenuItem("CSV");
		exportBGCSV.addClickHandler(new com.smartgwt.client.widgets.menu.events.ClickHandler() {			
			@Override
			public void onClick(MenuItemClickEvent arg0) {
				com.google.gwt.user.client.Window.open("/norabase/export?format=csv&bgid=" + bgts.getCurrentBattlegroupId(), "_blank", null);
			}
		});
		MenuItem exportBGHTML = new MenuItem("HTML");
		exportBGHTML.addClickHandler(new com.smartgwt.client.widgets.menu.events.ClickHandler() {			
			@Override
			public void onClick(MenuItemClickEvent arg0) {
				com.google.gwt.user.client.Window.open("/norabase/export?format=html&bgid=" + bgts.getCurrentBattlegroupId(), "_blank", null);
			}
		});
		exportBGSM.setItems(exportBGCSV, exportBGHTML);
		exportBGItem.setSubmenu(exportBGSM);

		MenuItem exportCollItem = new MenuItem("Export Collection as...");
		Menu exportCollSM = new Menu();
		MenuItem exportCollCSV = new MenuItem("CSV");
		exportCollCSV.addClickHandler(new com.smartgwt.client.widgets.menu.events.ClickHandler() {			
			@Override
			public void onClick(MenuItemClickEvent arg0) {
				com.google.gwt.user.client.Window.open("/norabase/export?format=csv&user=" + loginInfo.getAccount().getEmail(), "_blank", null);
			}
		});
		MenuItem exportCollHTML = new MenuItem("HTML");
		exportCollHTML.addClickHandler(new com.smartgwt.client.widgets.menu.events.ClickHandler() {			
			@Override
			public void onClick(MenuItemClickEvent arg0) {
				com.google.gwt.user.client.Window.open("/norabase/export?format=html&user=" + loginInfo.getAccount().getEmail(), "_blank", null);
			}
		});
		exportCollSM.setItems(exportCollCSV, exportCollHTML);
		exportCollItem.setSubmenu(exportCollSM);

		MenuItem importBGItem = new MenuItem("Import Battlegroup...");
		importBGItem.addClickHandler(new com.smartgwt.client.widgets.menu.events.ClickHandler() {			
			@Override
			public void onClick(MenuItemClickEvent arg0) {
				body.addChild(new ImportBattlegroupDialog(bgts));
			}
		});

		MenuItem importCollItem = new MenuItem("Import Collection as...");
		Menu importColl = new Menu();
		MenuItem importCollCSV = new MenuItem("CSV");
		importCollCSV.addClickHandler(new com.smartgwt.client.widgets.menu.events.ClickHandler() {			
			@Override
			public void onClick(MenuItemClickEvent arg0) {
				body.addChild(new ImportCollectionDialog(ImportCollectionDialog.CSV, bgts));
			}
		});
		MenuItem importCollPOX = new MenuItem("PoxNora System");
		importCollPOX.addClickHandler(new com.smartgwt.client.widgets.menu.events.ClickHandler() {			
			@Override
			public void onClick(MenuItemClickEvent arg0) {
				SC.say("<b>Warning</b><br>The collection import from the PoxNora system is an experimental feature and may break if Sony alters minor formatting in the PoxNora website. Please report errors to the NoraBase Issue Management System.<br>To import your collection, perform the following steps:" + 
							"<ul><li>Go to www.poxnora.com, log in and view the Runes Checklist</li><li>Make sure you display your entire collection on one page (for example by selecting a faction and then selecting <b>again</b> 'All Factions')</li><li>Save the page from your browser</li><li>Import the saved HTML page in the dialog which appears when you click 'Ok' below this text.</li></ul>");
				body.addChild(new ImportCollectionDialog(ImportCollectionDialog.POXNORA, bgts));
			}
		});
		importColl.setItems(importCollCSV, importCollPOX);
		importCollItem.setSubmenu(importColl);
		
		MenuItem showBGURL = new MenuItem("Show Battlegroup URL...");
		showBGURL.addClickHandler(new com.smartgwt.client.widgets.menu.events.ClickHandler() {			
			@Override
			public void onClick(MenuItemClickEvent arg0) {
				SC.say("The direct link to the battlegroup \"" + bgts.getCurrentBattlegroup().getName() + "\" is<p><center><a href='/b/" + bgts.getCurrentBattlegroupId() + "' target='_blank'>http://app.norabase.com/b/" + bgts.getCurrentBattlegroupId() + "</a></center><p>This link is accessible without an account, post this URL into forms posts, emails etc.");
			}
		});
		MenuItem showRuneURL = new MenuItem("Show Rune URL...");
		showRuneURL.addClickHandler(new com.smartgwt.client.widgets.menu.events.ClickHandler() {			
			@Override
			public void onClick(MenuItemClickEvent arg0) {
				String runeCode = getCurrentRuneRecord().getAttribute("type").substring(0,1).toLowerCase() + getCurrentRuneRecord().getAttribute("id");
				SC.say("The direct link to the rune \"" + getCurrentRuneRecord().getAttribute("name") + "\" is<p><center><a href='/r/" + runeCode + "' target='_blank'>http://app.norabase.com/r/" + runeCode + "</a></center><p>This link is accessible without an account, post this URL into forms posts, emails etc.");
			}
		});
		
		
		MenuItemSeparator separator = new MenuItemSeparator();

		menu.setItems(exportBGItem, exportCollItem, separator, importBGItem, importCollItem, separator, showBGURL, showRuneURL);

		return new ToolStripMenuButton("Extras", menu);
	}

	private ListGridRecord getCurrentRuneRecord() {
		Canvas c = databaseSet.getSelectedTab().getPane();
		if (c instanceof ListGrid) {
			return ((ListGrid)c).getSelectedRecord();
		}
		return null;
	}

	public void loadNoraBase() {

		body = new VLayout();
		body.setSize("100%", "100%");
		
		HLayout layout = new HLayout();
		layout.setSize("100%", "100%");

		final TabSet infoTabSet = new TabSet();  
		infoTabSet.setWidth("322px");
		infoTabSet.setHeight("100%");
		infoTabSet.setTabBarPosition(Side.BOTTOM);  
		Tab cardInfoTab = new Tab("Rune Info");
		
		VLayout infoArea = new VLayout();
		infoArea.setSize("270px", "100%");
		infoArea.setBackgroundColor("#000000");

		final FrontCard frontCard = new FrontCard();
		final BackCard backCard = new BackCard();
		infoArea.addMember(frontCard);
		infoArea.addMember(backCard);

		cardInfoTab.setPane(infoArea);

		final Tab cardCommentsTab = new Tab("Rune Comments");
		final RatingCanvas ratingCanvas = new RatingCanvas();
		cardCommentsTab.setPane(ratingCanvas);
		
		infoTabSet.addTab(cardInfoTab);
		infoTabSet.addTab(cardCommentsTab);
		layout.addMember(infoTabSet);

		VLayout managementArea = new VLayout();
		managementArea.setSize("100%", "100%");

		databaseSet.setSize("100%", "50%");

		final BattlegroupTabSet bgts = new BattlegroupTabSet();

		final ListGrid championsGrid = new RuneGrid(bgts);
		final ListGrid spellsGrid = new RuneGrid(bgts);
		final ListGrid equipmentGrid = new RuneGrid(bgts);
		final ListGrid relicsGrid = new RuneGrid(bgts);
		
		ToolStrip mainStrip = new ToolStrip();
		mainStrip.setWidth("100%");
		Label titleLabel = new Label("<b>&nbsp;NoraBase&nbsp;Editor&nbsp;-&nbsp;Battlegroup&nbsp;Editor&nbsp;for&nbsp;Pox&nbsp;Nora&nbsp;by&nbsp;<a href=\"mailto:michael@kleinhenz.net\">Michael&nbsp;Kleinhenz</a></b>");
		mainStrip.addMember(titleLabel);
		mainStrip.addFill();
		/* REMOVED FOR NOW
		 * ToolStripButton filterButton = new ToolStripButton("Advanced Rune Filter");
		filterButton.addClickHandler(new ClickHandler() {			
			@Override
			public void onClick(ClickEvent event) {
				body.addChild(new AdvancedFilterDialog((ListGrid)databaseSet.getSelectedTab().getPane()));
			}
		});
		mainStrip.addMember(filterButton);
		 */
		ToolStripButton savePrefsButton = new ToolStripButton("Save Table Preferences");
		savePrefsButton.addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				loginInfo.getAccount().setChampionGridPreference(championsGrid.getViewState());
				loginInfo.getAccount().setSpellGridPreference(spellsGrid.getViewState());
				loginInfo.getAccount().setEquipmentGridPreference(equipmentGrid.getViewState());
				loginInfo.getAccount().setRelicGridPreference(relicsGrid.getViewState());
				loginInfo.getAccount().setBattlegroupGridPreference(bgts.getViewState());
				LoginServiceAsync loginService = GWT.create(LoginService.class);
				loginService.update(loginInfo.getAccount(),
						new AsyncCallback<Void>() {
							public void onFailure(Throwable error) {
								SC.say("An error occured while saving preferences on the server. Please try again.");
							}

							public void onSuccess(Void v) {
							}
						});
			}
		});
		mainStrip.addMember(savePrefsButton);

		managementArea.addMember(mainStrip);
		
		Tab championsTab = new Tab("Champions");
		championsGrid.setSelectionType(SelectionStyle.SINGLE);
		championsGrid.setAutoFitFieldWidths(true);
		championsGrid.setMinFieldWidth(50);
		championsGrid.setAutoFetchData(true);
		championsGrid.setShowFilterEditor(true);  
		championsGrid.setFilterOnKeypress(true);
		championsGrid.setCanAddFormulaFields(true);  
		championsGrid.setCanAddSummaryFields(true);  
		championsTab.setPane(championsGrid);
		championsGrid.setDataSource(new ChampionsDS());
		setupColumns(championsGrid, Rune.CHAMPION);
		championsGrid.setViewState(loginInfo.getAccount().getChampionGridPreference());
		championsGrid.addClickHandler(new ClickHandler()
		{
			@Override
			public void onClick(ClickEvent event)
			{
				Canvas c = databaseSet.getSelectedTab().getPane();
				if (c instanceof ListGrid) {
					ListGridRecord record = ((ListGrid)c).getSelectedRecord();
					RuneLoader.loadChampion(record.getAttributeAsInt("id"), frontCard, backCard, ratingCanvas);
				} else
					throw new RuntimeException("Error: child of tab is not a grid: " + c);
			}
		});
		databaseSet.addTab(championsTab);

		Tab spellsTab = new Tab("Spells");
		spellsGrid.setSelectionType(SelectionStyle.SINGLE);
		spellsGrid.setAutoFitFieldWidths(true);
		spellsGrid.setMinFieldWidth(50);
		spellsGrid.setAutoFetchData(true);
		spellsGrid.setShowFilterEditor(true);  
		spellsGrid.setFilterOnKeypress(true);  
		spellsGrid.setCanAddFormulaFields(true);  
		spellsGrid.setCanAddSummaryFields(true);  
		spellsTab.setPane(spellsGrid);
		spellsGrid.setDataSource(new SpellDS());
		setupColumns(spellsGrid, Rune.SPELL);
		spellsGrid.setViewState(loginInfo.getAccount().getSpellGridPreference());
		spellsGrid.addClickHandler(new ClickHandler()
		{
			@Override
			public void onClick(ClickEvent event)
			{
				Canvas c = databaseSet.getSelectedTab().getPane();
				if (c instanceof ListGrid) {
					ListGridRecord record = ((ListGrid)c).getSelectedRecord();
					RuneLoader.loadSpell(record.getAttributeAsInt("id"), frontCard, backCard, ratingCanvas);
				} else
					throw new RuntimeException("Error: child of tab is not a grid: " + c);
			}
		});
		databaseSet.addTab(spellsTab);

		Tab equipmentTab = new Tab("Equipment");
		equipmentGrid.setSelectionType(SelectionStyle.SINGLE);
		equipmentGrid.setAutoFitFieldWidths(true);
		equipmentGrid.setMinFieldWidth(50);
		equipmentGrid.setAutoFetchData(true);
		equipmentGrid.setShowFilterEditor(true);  
		equipmentGrid.setFilterOnKeypress(true);  
		equipmentGrid.setCanAddFormulaFields(true);  
		equipmentGrid.setCanAddSummaryFields(true);  
		equipmentTab.setPane(equipmentGrid);
		equipmentGrid.setDataSource(new EquipmentDS());
		setupColumns(equipmentGrid, Rune.EQUIPMENT);
		equipmentGrid.setViewState(loginInfo.getAccount().getEquipmentGridPreference());
		equipmentGrid.addClickHandler(new ClickHandler()
		{
			@Override
			public void onClick(ClickEvent event)
			{
				Canvas c = databaseSet.getSelectedTab().getPane();
				if (c instanceof ListGrid) {
					ListGridRecord record = ((ListGrid)c).getSelectedRecord();
					RuneLoader.loadEquipment(record.getAttributeAsInt("id"), frontCard, backCard, ratingCanvas);
				} else
					throw new RuntimeException("Error: child of tab is not a grid: " + c);
			}
		});
		databaseSet.addTab(equipmentTab);

		Tab relicsTab = new Tab("Relics");
		relicsGrid.setSelectionType(SelectionStyle.SINGLE);
		relicsGrid.setAutoFitFieldWidths(true);
		relicsGrid.setMinFieldWidth(50);
		relicsGrid.setAutoFetchData(true);
		relicsGrid.setShowFilterEditor(true);  
		relicsGrid.setFilterOnKeypress(true);  
		relicsGrid.setCanAddFormulaFields(true);  
		relicsGrid.setCanAddSummaryFields(true);  
		relicsTab.setPane(relicsGrid);
		relicsGrid.setDataSource(new RelicDS());
		setupColumns(relicsGrid, Rune.RELIC);
		relicsGrid.setViewState(loginInfo.getAccount().getRelicGridPreference());
		relicsGrid.addClickHandler(new ClickHandler()
		{
			@Override
			public void onClick(ClickEvent event)
			{
				Canvas c = databaseSet.getSelectedTab().getPane();
				if (c instanceof ListGrid) {
					ListGridRecord record = ((ListGrid)c).getSelectedRecord();
					RuneLoader.loadRelic(record.getAttributeAsInt("id"), frontCard, backCard, ratingCanvas);
				} else
					throw new RuntimeException("Error: child of tab is not a grid: " + c);
			}
		});
		databaseSet.addTab(relicsTab);
		managementArea.addMember(databaseSet);

		bgts.setViewState(loginInfo.getAccount().getBattlegroupGridPreference());
		
		ToolStrip battlegroupToolbar = new ToolStrip();
		battlegroupToolbar.setWidth("100%");

		final ToolStripButton propsBGButton = new ToolStripButton("Battlegroup Properties", "/icons/propsBG.png");;
		final ToolStripButton commentsBGButton = new ToolStripButton("Battlegroup Comments", "/icons/commentBG.png");;
		final ToolStripButton closeBGButton = new ToolStripButton("Close Battlegroup", "/icons/closeBG.png");
		
		ToolStripButton newBGButton = new ToolStripButton("New Battlegroup", "/icons/addBG.png");
		newBGButton.addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				bgts.openTab(null, "New Battlegroup", loginInfo.getAccount().getBattlegroupGridPreference());
				propsBGButton.setDisabled(false);
				commentsBGButton.setDisabled(false);
				closeBGButton.setDisabled(false);
			}
		});
		battlegroupToolbar.addButton(newBGButton);
		ToolStripButton openBGButton = new ToolStripButton("Open Battlegroup", "/icons/openBG.png");
		openBGButton.addClickHandler(new ClickHandler() {			
			@Override
			public void onClick(ClickEvent event) {
					         new BattlegroupOpenDialog(bgts).show();
			}  
		});
		battlegroupToolbar.addButton(openBGButton);
		
		closeBGButton.setDisabled(true);
		closeBGButton.addClickHandler(new ClickHandler() {			
			@Override
			public void onClick(ClickEvent event) {
				if (bgts.getCurrentBattlegroup()!=null)
					bgts.closeTab(bgts.getCurrentBattlegroupId());
			}  
		});
		battlegroupToolbar.addButton(closeBGButton);
		
		battlegroupToolbar.addSeparator();
		ToolStripButton addRuneButton = new ToolStripButton("Add Rune", "/icons/addRune.png");
		addRuneButton.addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				Canvas c = databaseSet.getSelectedTab().getPane();
				if (c instanceof ListGrid) {
					ListGridRecord record = ((ListGrid)c).getSelectedRecord();
					bgts.addRune(record);
				} else
					throw new RuntimeException("Error: child of tab is not a grid: " + c);
			}
		});
		battlegroupToolbar.addButton(addRuneButton);
		ToolStripButton removeRuneButton = new ToolStripButton("Remove Rune", "/icons/removeRune.png");
		removeRuneButton.addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				Canvas c = bgts.getSelectedTab().getPane();
				if (c instanceof ListGrid) {
					ListGridRecord record = ((ListGrid)c).getSelectedRecord();
					bgts.removeRune(record);
				} else
					throw new RuntimeException("Error: child of tab is not a grid: " + c);
			}
		});
		battlegroupToolbar.addButton(removeRuneButton);

		battlegroupToolbar.addSeparator();
		propsBGButton.setDisabled(true);
		propsBGButton.addClickHandler(new ClickHandler() {			
			@Override
			public void onClick(ClickEvent event) {
					if (bgts.getCurrentBattlegroup()!=null)
				         body.addChild(new BattlegroupPropertiesDialog(bgts.getCurrentBattlegroup(), bgts));						
			}  
		});
		battlegroupToolbar.addButton(propsBGButton);

		commentsBGButton.setDisabled(true);
		commentsBGButton.addClickHandler(new ClickHandler() {			
			@Override
			public void onClick(ClickEvent event) {
					if (bgts.getCurrentBattlegroup()!=null)
				         body.addChild(new BattlegroupCommentsDialog(bgts.getCurrentBattlegroup()));						
			}  
		});
		battlegroupToolbar.addButton(commentsBGButton);

		battlegroupToolbar.addSeparator();
		battlegroupToolbar.addMenuButton(createMenu(bgts));
		
		battlegroupToolbar.addFill();
		ToolStripButton deleteBGButton = new ToolStripButton("Delete Battlegroup", "/icons/deleteBG.png");
		deleteBGButton.addClickHandler(new ClickHandler() {			
			@Override
			public void onClick(ClickEvent event) {
				if (bgts.getCurrentBattlegroup()!=null) {
					SC.ask("Are you sure that you want to delete the battlegroup named \"" + bgts.getCurrentBattlegroup().getName() + "\"? This can not be undone.", 
							new BooleanCallback() {
								@Override
								public void execute(Boolean value) {
									if (value==true) {
										BattlegroupServiceAsync battlegroupService = GWT.create(BattlegroupService.class);
										battlegroupService.deleteBattlegroup(bgts.getCurrentBattlegroup(),
												new AsyncCallback<Void>() {
													public void onFailure(Throwable error) {
														SC.say("An error occured while deleting battlegroup on the server. Please try again.");
													}
	
													public void onSuccess(Void result) {
														bgts.closeTab(bgts.getCurrentBattlegroupId());									
													}
												});
										}
									}
							});
					}
			}  
		});
		battlegroupToolbar.addButton(deleteBGButton);		
		
		managementArea.addMember(battlegroupToolbar);

		bgts.setSize("100%", "50%");
		managementArea.addMember(bgts);
		layout.addMember(managementArea);
		        
		body.addMember(layout);
	
		ToolStrip statusStrip = new ToolStrip();
        statusStrip.setWidth("100%");
        statusStrip.addFill();
		Label userLabel = new Label(loginInfo.getAccount().getEmail() + "&nbsp;<a href=\"" + loginInfo.getLogoutUrl() + "\">[Logout]</a>");
		statusStrip.addMember(userLabel);
		statusStrip.addSeparator();
		Label versionLabel = new Label("Version&nbsp;" + VERSION);
        statusStrip.addMember(versionLabel);
        
        body.addMember(statusStrip);
		
        RootPanel root = RootPanel.get("battlegroupEditor");
        if (root!=null)
        	root.add(body);
	}

	public static LoginInfo getLoginInfo() {
		return loginInfo;
	}
	
	private void setupColumns(ListGrid grid, String type) {

		ListGridField iconField = new ListGridField("icons", "Actions");
		iconField.setWidth(20);
		
		ListGridField nameField = new ListGridField("name");  
		nameField.setIncludeInRecordSummary(false);  
		
		ListGridField typeField = new ListGridField("type");  
		typeField.setIncludeInRecordSummary(true);  
		typeField.setSummaryFunction(new SummaryFunction() {
			@Override
			public Object getSummaryValue(Record[] records, ListGridField field) {
				return records.length + " Runes";
			}
		});

		ListGridField startingAbilitiesStringField = new ListGridField("startingAbilitiesString");  
		startingAbilitiesStringField.setIncludeInRecordSummary(false);
		startingAbilitiesStringField.setHidden(true);

		ListGridField upgradeAbilitiesStringField = new ListGridField("upgradeAbilitiesString");  
		upgradeAbilitiesStringField.setIncludeInRecordSummary(false);
		upgradeAbilitiesStringField.setHidden(true);

		ListGridField racesField = new ListGridField("races");  
		racesField.setIncludeInRecordSummary(false);
		racesField.setHidden(true);
		
		ListGridField classesField = new ListGridField("classes");  
		classesField.setIncludeInRecordSummary(false);
		classesField.setHidden(true);
		
		ListGridField sizeField = new ListGridField("size");  
		sizeField.setIncludeInRecordSummary(false);
		sizeField.setHidden(true);
		
		ListGridField maxrngField = new ListGridField("maxrng");  
		maxrngField.setIncludeInRecordSummary(false);
		
		ListGridField minrngField = new ListGridField("minrng");  
		minrngField.setIncludeInRecordSummary(false);
		
		ListGridField spdField = new ListGridField("spd");  
		spdField.setIncludeInRecordSummary(false);
		
		ListGridField defField = new ListGridField("def");  
		defField.setIncludeInRecordSummary(false);
		
		ListGridField dmgField = new ListGridField("dmg");  
		dmgField.setIncludeInRecordSummary(false);
		
		ListGridField hpField = new ListGridField("hp");  
		hpField.setIncludeInRecordSummary(false);
		
		ListGridField expansionField = new ListGridField("expansion");  
		expansionField.setIncludeInRecordSummary(false);
		
		ListGridField factionField = new ListGridField("faction");  
		factionField.setIncludeInRecordSummary(false);

		ListGridField artistField = new ListGridField("artist");  
		artistField.setIncludeInRecordSummary(false);
		artistField.setHidden(true);
		
		ListGridField noraField = new ListGridField("nora");  
		noraField.setIncludeInRecordSummary(false);
		
		ListGridField rarityField = new ListGridField("rarity");  
		rarityField.setIncludeInRecordSummary(false);
		
		ListGridField ownedField = new ListGridField("owned");  
		ownedField.setIncludeInRecordSummary(false);

		ListGridField descField = new ListGridField("desc");  
		descField.setIncludeInRecordSummary(false);
		descField.setHidden(true);

		ListGridField cooldownField = new ListGridField("cooldown");  
		cooldownField.setIncludeInRecordSummary(false);

		if (Rune.CHAMPION.equals(type))
			grid.setFields(iconField, nameField, expansionField, factionField, startingAbilitiesStringField, upgradeAbilitiesStringField, 
				racesField, classesField, sizeField, maxrngField, minrngField, spdField, defField, dmgField,
				hpField, artistField, noraField, rarityField, ownedField);
		else if (Rune.EQUIPMENT.equals(type))
			grid.setFields(iconField, nameField, expansionField, factionField, artistField, noraField, rarityField, descField, ownedField);
		else if (Rune.SPELL.equals(type))
			grid.setFields(iconField, nameField, expansionField, factionField, artistField, cooldownField, noraField, rarityField, descField, ownedField);
		else if (Rune.RELIC.equals(type))
			grid.setFields(iconField, nameField, expansionField, factionField, defField, hpField, artistField, noraField, rarityField, descField, ownedField);
	}
}
